<?php

declare(strict_types=1);

namespace catchAdmin\monitor\command;

use Carbon\Carbon;
use catchAdmin\basics\model\Company;
use catchAdmin\basics\model\StorageFeeConfig;
use catchAdmin\basics\model\StorageFeeConfigInfo;
use catchAdmin\product\model\Product;
use catchAdmin\settlement\model\StorageFee;
use catchAdmin\settlement\model\StorageProductFee;
use catchAdmin\warehouse\model\WarehouseOrderProducts;
use catchAdmin\warehouse\model\WarehouseStock;
use catchAdmin\warehouse\model\WarehouseStockLogs;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Log;
use catcher\Code;
use think\facade\Db;

class StorageFeeCommand extends Command
{
    protected $pid;

    protected function configure()
    {
        // 指令配置
        $this->setName('catch:storageFee')
            ->setDescription('get storage fee list');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $this->executeCommand();
        } catch (\Exception $e) {
            Log::error('StorageFee Error Line:' . $e->getLine());
            Log::error('StorageFee Error Code:' . $e->getCode());
            Log::error('StorageFee Error Message:' . $e->getMessage());
            throw new \Exception($e->getLine() . "----" . $e->getMessage());
        }
    }

    /**
     * 执行 command
     *
     * @time 2021年03月02日
     * @return void
     */
    protected function executeCommand()
    {
        $companys = Company::select();


        foreach ($companys as $company) {

            //按公司计算并存储仓储费
            $storageFee = StorageFee::where('company_id', $company->id)->find();
            if (!$storageFee) {
                $storageFee = StorageFee::create([
                    'company_id' => $company->id,
                    'company_name' => $company->getAttr('name'),
                    'company_code' => $company->code,
                    'company_type' => $company->type,
                ]);
            }
            //获取所有商品
            $products = Product::where('company_id', $company->id)->select();


            foreach ($products as  $product) {

                //获取商品所有批次
                $stock = WarehouseStock::alias('ws')
                    ->leftJoin('warehouses w', 'w.id=ws.virtual_warehouse_id')
                    ->where('goods_code', $product->code)
                    ->where('w.type', '<>', 3)
                    ->select();

                if (count($stock) == 0) {
                    continue;
                }


                //计算每个批次的入库时长
                foreach ($stock as $val) {
                    $warehousingTime = '';
                    if ($val->number > 0) {
                        $orderProduct = WarehouseOrderProducts::alias('wop')
                            ->leftJoin('warehouse_orders wo', 'wo.id=wop.warehouse_order_id')
                            ->where([
                                'wop.batch_no' => $val->batch_no,
                                'wop.goods_code' => $val->goods_code,
                                'wo.warehousing_status' => 1
                            ])
                            ->whereTime('wo.warehousing_time', '>', '2022-01-01')
                            ->order('wop.id', 'desc')
                            ->find();

                        if ($orderProduct) {
                            $warehousingTime = $orderProduct->warehousing_time; //入库时间
                        } else {
                            $warehousingTime = '2022-01-01';
                        }


                        $diffDays = Carbon::parse($warehousingTime)->diffInDays(); //入库时长

                        //计算仓库费
                        $storageConfig = StorageFeeConfigInfo::alias('sfci')
                            ->leftJoin('storage_fee_config sfc', 'sfc.id=sfci.fee_config_id')
                            ->where([
                                'sfc.company_id' => $company->id,
                                'sfc.is_status' => 1
                            ])
                            ->where('sfci.min_days', '<=', $diffDays)
                            ->where('sfci.max_days', '>=', $diffDays)
                            //  ->where('warehouse_id', 'like', "%" . $val->virtual_warehouse_id . "%")
                            ->whereRaw("FIND_IN_SET(" . $val->virtual_warehouse_id . ", sfci.warehouse_id)")
                            ->find();

                        if ($storageConfig && $storageConfig->fee > 0) {
                            $fee = number_format($product->info->volume
                                * $val->number
                                * $storageConfig->fee, 2);

                            StorageProductFee::create([
                                'storage_fee_id' => $storageFee->id,
                                'virtual_warehouse_id' => $val->virtual_warehouse_id,
                                'goods_code' => $product->code,
                                'goods_name' => $product->name_ch,
                                'batch_no' => $val->batch_no,
                                'storage_number' => $val->number,
                                'warehousing_time' => $warehousingTime,
                                'storage_days' => $diffDays,
                                'fee' => $fee,
                                'department_id' =>
                                $val->department_id
                            ]);

                            /**
                             * 扣费条件
                             * 1 有所属组织 ，无所属客户 计算仓储费，不扣额度
                             * 2 无所属组织 ，有所属客户  计算仓储费，扣额度
                             */

                            if ($val->company_id && $fee > 0) {
                                $company = Company::find($val->company_id);
                                $company->amountDeduction($fee, $val->company_id);
                            }
                        }
                    }
                }
            }
        }
    }
}
